import React, { useRef, useState } from "react";
import styles from "./index.module.scss";
import { Input, Modal, message } from "antd";
import UploadBase from "../UploadBase";
import { upload } from "@/api";
import ReactQuill from "react-quill";
import { SEVER_URL, formats, modules } from "@/configs/constant";
import "react-quill/dist/quill.snow.css";

import "./index.css";
type TCourse = {
  courseName: string;
  setCourseName: (value: string) => void;
  videoUrl: string;
  setVedioUrl: (value: string) => void;
  courseId?: number;
};
type TModal = {
  open: boolean;
  onOk: () => void;
  onCancel: () => void;
  contentCourse?: string;
  handleChangeValue?: (value: string) => void;
};
type TCourseModal = TCourse & TModal;
const CourseModal = (props: TCourseModal) => {
  const {
    open,
    onOk,
    onCancel,
    courseName,
    setCourseName,
    videoUrl,
    setVedioUrl,
    courseId,
    contentCourse,
    handleChangeValue,
  } = props;
  const quillRef = useRef<ReactQuill>(null);
  const inputRef = useRef(null);
  async function uploadCom(e: React.ChangeEvent<HTMLInputElement>) {
    if (e.target.files) {
      const files = e.target.files[0];
      var formData = new FormData();
      formData.append("files", files);
      const response = await upload(formData);
      if (response.data.code === 200) {
        setVedioUrl(response.data.data[0]);
        message.success(response.data.msg);
      } else {
        message.error(response.data.msg);
      }
    }
  }
  const classNames = {
    body: styles["my-modal-body"],
  };
  const quillUploadVideo = () => {
    const input = document.createElement("input");
    input.setAttribute("type", "file");
    input.setAttribute("accept", "video/*");
    input.click();
    input.onchange = async () => {
      const file = input.files?.[0];
      if (file) {
        const formData = new FormData();
        formData.append("files", file);
        try {
          const response = await upload(formData);
          const videoUrl = response.data.data[0];
          const quill = quillRef.current?.getEditor();
          // const cursorPosition = quill?.selection.savedRange.index;
          const range = quill?.getSelection();
          debugger;

          if (range) {
            quill?.insertEmbed(range.index, "video", `${SEVER_URL}${videoUrl}`);
            quill?.setSelection(range.index + 1);
            debugger;
          }
        } catch (error) {
          message.error("视频上传失败");
        }
      }
    };
  };
  const inputOnChange = async (e: any) => {
    const file = e.target.files?.[0];
    if (file) {
      const formData = new FormData();
      formData.append("files", file);
      try {
        const response = await upload(formData);
        const videoUrl = response.data.data[0];
        const quill = quillRef.current?.getEditor();
        const cursorPosition = quill?.selection.savedRange.index;
        if (cursorPosition) {
          quill?.insertEmbed(
            cursorPosition,
            "video",
            `${SEVER_URL}${videoUrl}`
          );
          quill.setSelection(cursorPosition + 1);
        }
      } catch (error) {
        message.error("视频上传失败");
      }
    }
  };

  // 富文本编辑器配置
  const module = {
    toolbar: {
      handlers: {
        video: quillUploadVideo,
      },
      container: [
        [{ header: [1, 2, 3, false] }],
        ["bold", "italic", "underline", "strike"],
        ["blockquote", "code-block"],
        [{ list: "ordered" }, { list: "bullet" }],
        ["link", "image", "video"], // 默认图片按钮
        ["clean"],
      ],
    },
  };

  return (
    <>
      <Modal
        open={open}
        onOk={onOk}
        onCancel={onCancel}
        title={courseId ? "编辑编程课程内容" : "添加编程课程内容"}
        classNames={classNames}
        okText={"确定"}
        cancelText={"取消"}
      >
        <div className={styles["row-wrapper"]}>
          <span>上传编程课程视频</span>
          <UploadBase onChange={(e) => uploadCom(e)} videoUrl={videoUrl} />
        </div>
        {/* <input
          type="file"
          ref={inputRef}
          accept="video/*"
          style={{ display: "block" }}
          onChange={inputOnChange}
        /> */}
        <div className={styles["row-wrapper"]}>
          <span>编程课程内容名称</span>
          <Input
            value={courseName}
            onChange={(e) => setCourseName(e.target.value)}
            style={{ maxWidth: 240 }}
          ></Input>
        </div>
        <div className={styles["content"]}>
          <ReactQuill
            placeholder="请输入你想编辑的内容"
            theme="snow"
            value={contentCourse}
            onChange={handleChangeValue}
            formats={formats}
            modules={module}
            ref={quillRef}
          />
          <div className={styles["editorFooter"]}></div>
        </div>
      </Modal>
    </>
  );
};
export default CourseModal;
